﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Sale_Model;
using Sale_Common;
using Sale_DAL;

namespace Sale_Operation
{
    public class AccountRecordOp : Component
    {
        public override bool Save(object obj)
        {
            db = new DataBase();
            bool blRes = false;
            AccountRecord SM = obj as AccountRecord;
            int iold = SM.ARecoId;
            try
            {
                StringBuilder sbSql = new StringBuilder();
                if (SM.ARecoId == 0)
                {
                    sbSql.Append("INSERT INTO AccountRecord (AReco_Code,AReco_OutNumber,AReco_InNumber,AReco_Noney,AReco_Type,AReco_Reason,AReco_Man,AReco_Kind,AReco_Datetime,State,CreateTime,CreateMan) SELECT ");
                    sbSql.Append("AReco_Code='" + ValueHandler.GetStringValue(SM.AReco_Code, ValueHandler.CharHandlerType.IsRepChar) + "',");
                    sbSql.Append("AReco_OutNumber='" + ValueHandler.GetStringValue(SM.AReco_OutNumber, ValueHandler.CharHandlerType.IsRepChar) + "',");
                    sbSql.Append("AReco_InNumber='" + ValueHandler.GetStringValue(SM.AReco_InNumber, ValueHandler.CharHandlerType.IsRepChar) + "',");
                    sbSql.Append("AReco_Noney=" + ValueHandler.GetStringValue(SM.AReco_Noney, ValueHandler.CharHandlerType.IsRepChar) + ",");
                    sbSql.Append("AReco_Type='" + ValueHandler.GetStringValue(SM.AReco_Type, ValueHandler.CharHandlerType.IsRepChar) + "',");
                    sbSql.Append("AReco_Reason='" + ValueHandler.GetStringValue(SM.AReco_Reason, ValueHandler.CharHandlerType.IsRepChar) + "',");
                    sbSql.Append("AReco_Man='" + ValueHandler.GetStringValue(SM.AReco_Man, ValueHandler.CharHandlerType.IsRepChar) + "',");
                    sbSql.Append("AReco_Kind='" + ValueHandler.GetStringValue(SM.AReco_Kind, ValueHandler.CharHandlerType.IsRepChar) + "',");
                    sbSql.Append("AReco_Datetime='" + ValueHandler.GetStringValue(SM.AReco_Datetime, ValueHandler.CharHandlerType.IsRepChar) + "',");
                    sbSql.Append("State='" + ValueHandler.GetStringValue(SM.State, ValueHandler.CharHandlerType.IsRepChar) + "',");
                    sbSql.Append("CreateTime=getdate(),");
                    sbSql.Append("CreateMan=" + LinkService.GetCurrentUser().SUser_Id);
                    db.Open();
                    SqlHelper.ExecuteNonQuery(db.Transaction, CommandType.Text, sbSql.ToString());
                    SM.ARecoId = ValueHandler.GetIntNumberValue(SqlHelper.ExecuteScalar(db.Transaction, CommandType.Text, "select @@identity "));
                    //将金额信息反映到帐户中
                    //存款
                    if (SM.AReco_Type == 1)
                    {
                        sbSql = new StringBuilder();
                        sbSql.Append(" UPDATE AccountList SET AList_Money=AList_Money+" + SM.AReco_Noney.ToString() + " WHERE AList_Id="+SM.AReco_InNumber);
                        SqlHelper.ExecuteNonQuery(db.Transaction, CommandType.Text, sbSql.ToString());                        
                    }
                    else if (SM.AReco_Type == 2)//取款
                    {
                        sbSql = new StringBuilder();
                        sbSql.Append(" UPDATE AccountList SET AList_Money=AList_Money-" + SM.AReco_Noney.ToString() + " WHERE AList_Id=" + SM.AReco_OutNumber);
                        SqlHelper.ExecuteNonQuery(db.Transaction, CommandType.Text, sbSql.ToString());                        
                    }
                    else if (SM.AReco_Type == 3)//转账
                    {
                        //先取出，后存
                        sbSql = new StringBuilder();
                        sbSql.Append(" UPDATE AccountList SET AList_Money=AList_Money-" + SM.AReco_Noney.ToString() + " WHERE AList_Id=" + SM.AReco_OutNumber);
                        SqlHelper.ExecuteNonQuery(db.Transaction, CommandType.Text, sbSql.ToString());
                        sbSql = new StringBuilder();
                        sbSql.Append(" UPDATE AccountList SET AList_Money=AList_Money+" + SM.AReco_Noney.ToString() + " WHERE AList_Id=" + SM.AReco_InNumber);
                        SqlHelper.ExecuteNonQuery(db.Transaction, CommandType.Text, sbSql.ToString());   
                    }
                }
                else
                {
                    //先取出更新数据前的该数据信息
                    AccountRecord SMOld = new AccountRecord();
                    SMOld.ARecoId = SM.ARecoId;
                    GetModel(SMOld);
                    sbSql.Append("UPDATE AccountRecord SET ");
                    sbSql.Append("AReco_Code='" + ValueHandler.GetStringValue(SM.AReco_Code, ValueHandler.CharHandlerType.IsRepChar) + "',");
                    sbSql.Append("AReco_OutNumber='" + ValueHandler.GetStringValue(SM.AReco_OutNumber, ValueHandler.CharHandlerType.IsRepChar) + "',");
                    sbSql.Append("AReco_InNumber='" + ValueHandler.GetStringValue(SM.AReco_InNumber, ValueHandler.CharHandlerType.IsRepChar) + "',");
                    sbSql.Append("AReco_Noney=" + ValueHandler.GetStringValue(SM.AReco_Noney, ValueHandler.CharHandlerType.IsRepChar) + ",");
                    sbSql.Append("AReco_Type='" + ValueHandler.GetStringValue(SM.AReco_Type, ValueHandler.CharHandlerType.IsRepChar) + "',");
                    sbSql.Append("AReco_Reason='" + ValueHandler.GetStringValue(SM.AReco_Reason, ValueHandler.CharHandlerType.IsRepChar) + "',");
                    sbSql.Append("AReco_Man='" + ValueHandler.GetStringValue(SM.AReco_Man, ValueHandler.CharHandlerType.IsRepChar) + "',");
                    sbSql.Append("AReco_Datetime='" + ValueHandler.GetStringValue(SM.AReco_Datetime, ValueHandler.CharHandlerType.IsRepChar) + "'");
                    sbSql.Append("WHERE ARecoId=" + SM.ARecoId);
                    db.Open();
                    SqlHelper.ExecuteNonQuery(db.Transaction, CommandType.Text, sbSql.ToString());
                    //将金额信息反映到帐户中（如果交易方式、交易金额、转出帐户、转入帐户有一个发生变化，那么金额信息将会发生变化）
                    if (SM.AReco_Noney != SMOld.AReco_Noney || SM.AReco_Type != SMOld.AReco_Type || SM.AReco_InNumber != SMOld.AReco_InNumber || SM.AReco_OutNumber != SMOld.AReco_OutNumber)
                    {
                       //1)先还原该单据之前的各个帐户数据（即没有该单据的时候，系统帐户的数据,通过之前的数据进行还原）
                        if (SMOld.AReco_Type == 1)//如原来是存，则现在从存款帐户扣除存款金额
                        {
                            sbSql = new StringBuilder();
                            sbSql.Append(" UPDATE AccountList SET AList_Money=AList_Money-" + SMOld.AReco_Noney.ToString() + " WHERE AList_Id=" + SMOld.AReco_InNumber);
                            SqlHelper.ExecuteNonQuery(db.Transaction, CommandType.Text, sbSql.ToString());     
                        }
                        else if (SMOld.AReco_Type == 1)//如果原来是取，则现在在取款帐户中存入取出的金额
                        {
                            sbSql = new StringBuilder();
                            sbSql.Append(" UPDATE AccountList SET AList_Money=AList_Money+" + SMOld.AReco_Noney.ToString() + " WHERE AList_Id=" + SMOld.AReco_OutNumber);
                            SqlHelper.ExecuteNonQuery(db.Transaction, CommandType.Text, sbSql.ToString());  
                        }
                        else if (SMOld.AReco_Type == 3)//如果原来是内部转账，那么正好将转入转出的帐号互换即可
                        {
                            //先取出，后存
                            sbSql = new StringBuilder();
                            sbSql.Append(" UPDATE AccountList SET AList_Money=AList_Money-" + SMOld.AReco_Noney.ToString() + " WHERE AList_Id=" + SMOld.AReco_InNumber);
                            SqlHelper.ExecuteNonQuery(db.Transaction, CommandType.Text, sbSql.ToString());
                            sbSql = new StringBuilder();
                            sbSql.Append(" UPDATE AccountList SET AList_Money=AList_Money+" + SMOld.AReco_Noney.ToString() + " WHERE AList_Id=" + SMOld.AReco_OutNumber);
                            SqlHelper.ExecuteNonQuery(db.Transaction, CommandType.Text, sbSql.ToString());
                        }
                       //2)然后按照新的交易规则及其交易金额存入数据
                        if (SM.AReco_Type == 1)
                        {
                            sbSql = new StringBuilder();
                            sbSql.Append(" UPDATE AccountList SET AList_Money=AList_Money+" + SM.AReco_Noney.ToString() + " WHERE AList_Id=" + SM.AReco_InNumber);
                            SqlHelper.ExecuteNonQuery(db.Transaction, CommandType.Text, sbSql.ToString());
                        }
                        else if (SM.AReco_Type == 2)//取款
                        {
                            sbSql = new StringBuilder();
                            sbSql.Append(" UPDATE AccountList SET AList_Money=AList_Money-" + SM.AReco_Noney.ToString() + " WHERE AList_Id=" + SM.AReco_OutNumber);
                            SqlHelper.ExecuteNonQuery(db.Transaction, CommandType.Text, sbSql.ToString());
                        }
                        else if (SM.AReco_Type == 3)//转账
                        {
                            //先取出，后存
                            sbSql = new StringBuilder();
                            sbSql.Append(" UPDATE AccountList SET AList_Money=AList_Money-" + SM.AReco_Noney.ToString() + " WHERE AList_Id=" + SM.AReco_OutNumber);
                            SqlHelper.ExecuteNonQuery(db.Transaction, CommandType.Text, sbSql.ToString());
                            sbSql = new StringBuilder();
                            sbSql.Append(" UPDATE AccountList SET AList_Money=AList_Money+" + SM.AReco_Noney.ToString() + " WHERE AList_Id=" + SM.AReco_InNumber);
                            SqlHelper.ExecuteNonQuery(db.Transaction, CommandType.Text, sbSql.ToString());
                        }
                    }
                }    
                db.Transaction.Commit();
                blRes = true;
                if (iold == 0)
                {
                    LinkService.InsertLog(ESysLogType.Operation, "新增转账单信息[" + ValueHandler.GetStringValue(SM.AReco_Code, ValueHandler.CharHandlerType.IsRepChar) + "]！", EMenuList.转账管理);

                }
                else
                {
                    LinkService.InsertLog(ESysLogType.Operation, "修改转账单信息[" + ValueHandler.GetStringValue(SM.AReco_Code, ValueHandler.CharHandlerType.IsRepChar) + "]！", EMenuList.转账管理);
                }

            }
            catch (Exception ex)
            {
                db.Transaction.Rollback();
                LinkService.InsertLog(ESysLogType.Error, "新增/修改转账信息出错！[" + ex.ToString() + "]", EMenuList.转账管理);
            }
            db.Close();
            return blRes;
        }

        public override bool HasExists(object obj)
        {
            bool blRes = true;
            try
            {
                AccountRecord SM = obj as AccountRecord;                
                StringBuilder sbSql = new StringBuilder();
                sbSql.Append(" SELECT * FROM AccountRecord WHERE AReco_Code='" + SM.AReco_Code + "' AND ARecoId<>" + SM.ARecoId + " AND State=1");
                SqlHelper.FillDataset(db.Connection, CommandType.Text, sbSql.ToString(), db.Data, new string[] { "dtList" });
                if (db.Data.Tables[0].Rows.Count > 0)
                    blRes = true;
                else
                    blRes = false;
            }
            catch (Exception ex)
            {
            }
            db.Close();
            return blRes;
        }

        public override bool Delete(object obj)
        {

            bool blRes = false;
            try
            {
                db = new DataBase();
                AccountRecord SMOld = GetModel(obj) as AccountRecord;
                StringBuilder sbSql = new StringBuilder();
                db.Open();
                sbSql.Append(" UPDATE AccountRecord SET State = 0 WHERE ARecoId=" + SMOld.ARecoId);
                SqlHelper.ExecuteNonQuery(db.Transaction, CommandType.Text, sbSql.ToString());
                //还原金额
                if (SMOld.AReco_Type == 1)//如原来是存，则现在从存款帐户扣除存款金额
                {
                    sbSql = new StringBuilder();
                    sbSql.Append(" UPDATE AccountList SET AList_Money=AList_Money-" + SMOld.AReco_Noney.ToString() + " WHERE AList_Id=" + SMOld.AReco_InNumber);
                    SqlHelper.ExecuteNonQuery(db.Transaction, CommandType.Text, sbSql.ToString());
                }
                else if (SMOld.AReco_Type == 1)//如果原来是取，则现在在取款帐户中存入取出的金额
                {
                    sbSql = new StringBuilder();
                    sbSql.Append(" UPDATE AccountList SET AList_Money=AList_Money+" + SMOld.AReco_Noney.ToString() + " WHERE AList_Id=" + SMOld.AReco_OutNumber);
                    SqlHelper.ExecuteNonQuery(db.Transaction, CommandType.Text, sbSql.ToString());
                }
                else if (SMOld.AReco_Type == 3)//如果原来是内部转账，那么正好将转入转出的帐号互换即可
                {
                    //先取出，后存
                    sbSql = new StringBuilder();
                    sbSql.Append(" UPDATE AccountList SET AList_Money=AList_Money-" + SMOld.AReco_Noney.ToString() + " WHERE AList_Id=" + SMOld.AReco_InNumber);
                    SqlHelper.ExecuteNonQuery(db.Transaction, CommandType.Text, sbSql.ToString());
                    sbSql = new StringBuilder();
                    sbSql.Append(" UPDATE AccountList SET AList_Money=AList_Money+" + SMOld.AReco_Noney.ToString() + " WHERE AList_Id=" + SMOld.AReco_OutNumber);
                    SqlHelper.ExecuteNonQuery(db.Transaction, CommandType.Text, sbSql.ToString());
                }
                db.Transaction.Commit();
                blRes = true;
                LinkService.InsertLog(ESysLogType.Operation, "转账单["+SMOld.AReco_Code+"]删除完成！", EMenuList.转账管理);
            }
            catch (Exception ex)
            {
                db.Transaction.Rollback();
                LinkService.InsertLog(ESysLogType.Error, "转账单删除出错！["+ex.ToString()+"]", EMenuList.转账管理);
            }
            db.Close();
            return blRes;

        }

        public override DataTable GetList(string strCondition, int iCurrentPageIndex, ref int iRecordCount)
        {
            try
            {
                db = new DataBase();
                StringBuilder sbSql = new StringBuilder();
                sbSql.Append(" SELECT ARecoId,AReco_Code,AReco_OutNumber,AReco_InNumber,AReco_Noney,AReco_Type,AReco_Reason,AReco_Man,AReco_Datetime,A.State,A.CreateTime,A.CreateMan ,B.AList_Name AS AReco_OutNumberName,C.AList_Name AS AReco_InNumberName,D.Name,CASE AReco_Kind WHEN 1 THEN '手工' ELSE  '自动' END AS AReco_KindName,AReco_Kind FROM AccountRecord A  ");
                sbSql.Append(" LEFT JOIN AccountList B ON (A.AReco_OutNumber = B.AList_Id )");
                sbSql.Append(" LEFT JOIN AccountList C ON (A.AReco_InNumber =C.AList_Id) ");
                sbSql.Append(" LEFT JOIN View_RecordType D ON (A.AReco_Type=D.Id)");
                sbSql.Append(" WHERE A.State= 1");
                if (!string.IsNullOrEmpty(strCondition))
                {
                    sbSql.Append(" AND " + strCondition);
                }
                sbSql.Append(" ORDER BY A.CreateTime DESC ");
                db.Data = SqlHelper.FillDataSet(db.Connection, sbSql.ToString(), iCurrentPageIndex, ref iRecordCount, LinkService.PageSize);
            }
            catch (Exception ex)
            {
                LinkService.InsertLog(ESysLogType.Error, "转账记录加载失败！[" + ex.ToString() + "]", EMenuList.转账管理);
            }
            db.Close();
            return db.Data.Tables[0];
        }
        public DataTable GetView_RecordType()
        {
            try
            {
                db = new DataBase();
                StringBuilder sbSql = new StringBuilder();
                sbSql.Append(" SELECT ID,NAME FROM View_RecordType  ");
                SqlHelper.FillDataset(db.Connection, CommandType.Text, sbSql.ToString(), db.Data, new string[] { "dtList"});
            }
            catch (Exception ex)
            {
                LinkService.InsertLog(ESysLogType.Error, "转账类型加载失败！[" + ex.ToString() + "]", EMenuList.转账管理);
            }
            db.Close();
            return db.Data.Tables[0];
        }

        public override object GetModel(object obj)
        {
            AccountRecord SM = obj as AccountRecord;
            db = new DataBase();
            try
            {
                
                StringBuilder sbSql = new StringBuilder();
                sbSql.Append(" SELECT ARecoId,AReco_Code,AReco_OutNumber,AReco_InNumber,AReco_Noney,AReco_Type,AReco_Reason,AReco_Man,AReco_Datetime,A.State,A.CreateTime,A.CreateMan ,B.AList_Name AS AReco_OutNumberName,C.AList_Name AS AReco_InNumberName,D.Name FROM AccountRecord A  ");
                sbSql.Append(" LEFT JOIN AccountList B ON (A.AReco_OutNumber = B.AList_Id )");
                sbSql.Append(" LEFT JOIN AccountList C ON (A.AReco_InNumber =C.AList_Id) ");
                sbSql.Append(" LEFT JOIN View_RecordType D ON (A.AReco_Type=D.Id)");
                sbSql.Append(" WHERE A.State= 1 AND ARecoId=" + SM.ARecoId);
                SqlHelper.FillDataset(db.Connection, CommandType.Text, sbSql.ToString(), db.Data, new string[] { "dtList"});
                if (db.Data.Tables[0].Rows.Count > 0)
                {
                    DataRow dr = db.Data.Tables[0].Rows[0];
                    SM.AReco_Code = ValueHandler.GetStringValue(dr["AReco_Code"]);
                    SM.AReco_Datetime = DateTime.Parse(dr["AReco_Datetime"].ToString());
                    SM.AReco_InNumber = ValueHandler.GetIntNumberValue(dr["AReco_InNumber"]);
                    SM.AReco_Man = ValueHandler.GetIntNumberValue(dr["AReco_Man"]);
                    SM.AReco_Noney = ValueHandler.GetDecNumberValue(dr["AReco_Noney"]);
                    SM.AReco_OutNumber = ValueHandler.GetIntNumberValue(dr["AReco_OutNumber"]);
                    SM.AReco_Reason = ValueHandler.GetStringValue(dr["AReco_Reason"]);
                    SM.AReco_Type = ValueHandler.GetIntNumberValue(dr["AReco_Type"]);
                    SM.ARecoId = ValueHandler.GetIntNumberValue(dr["ARecoId"]);
                    SM.CreateMan = ValueHandler.GetIntNumberValue(dr["CreateMan"]);
                    SM.CreateTime =DateTime.Parse(dr["CreateTime"].ToString());
                    SM.State = ValueHandler.GetIntNumberValue(dr["State"]);
                }
            }
            catch (Exception ex)
            {
                LinkService.InsertLog(ESysLogType.Error, "转账记录加载失败！[" + ex.ToString() + "]", EMenuList.转账管理);
            }
            db.Close();
            return SM;
        }
    }
}
